<template>
	<view class="detail">
		<view class="container">
			<!-- getOne:数组转对象 -->
			<!-- 	<unicloud-db :where="`_id=='${artid}'`" v-slot:default="{ data, loading, error, options }" :getone="true" :collection="collections">
				<view v-if="error">{{ error.message }}</view>
				
				<view v-else-if="loading">
					<u-skeleton rows="5" loading title></u-skeleton>
				</view>
				<view v-else>
					<view class="title">{{ data.title }}</view>
					<view class="userinfo">
						<view class="avatar">
							<image :src="data.user_id[0].avatar_file || '../../static/images/panda.jpg'" mode="aspectFill"></image>
						</view>
						<view class="text">
							<view class="name">{{ data.user_id[0].nickname || data.user_id[0].username }}</view>
							<view class="small">
								<uni-dateformat :date="data.publish_date" format="yyyy年MM月dd hh:mm:ss"></uni-dateformat>
								· 发布于{{ data.province }}
							</view>
						</view>
					</view>
					<view class="content">
						<u-parse :content="data.content" :tagStyle="tagStyle"></u-parse>
					</view>
				</view>
			</unicloud-db> -->
			<view v-if="loadState">
				<!-- 骨架屏 -->
				<u-skeleton rows="5" loading title></u-skeleton>
			</view>
			<view v-else>
				<view class="title">{{ detailObj.title }}</view>
				<view class="userinfo">
					<view class="avatar">
						<image :src="giveAvatar(detailObj)" mode="aspectFill"></image>
					</view>
					<view class="text">
						<view class="name">{{ giveName(detailObj) }}</view>
						<view class="small">
							<uni-dateformat :date="detailObj.publish_date" format="yyyy年MM月dd hh:mm:ss"></uni-dateformat>
							· 发布于{{ detailObj.province }}
						</view>
					</view>
				</view>
				<view class="content">
					<u-parse :content="detailObj.content" :tagStyle="tagStyle"></u-parse>
				</view>

				<view class="like">
					<view class="btn" :class="detailObj.isLike ? 'active' : ''" @click="clickLike">
						<text class="iconfont icon-good-fill"></text>
						<text v-if="detailObj.like_count > 0">{{ detailObj.like_count }}</text>
					</view>
					<view class="users">
						<template v-for="item in likeUserArr">
							<image v-if="item.user_id[0].avatar_file" type="image" :src="giveAvatar(item)" alt=""></image>
						</template>
						<image src="../../static/images/user.jpg" mode="aspectFill"></image>
					</view>
					<view class="text">
						<text class="num">{{ detailObj.view_count }}</text>
						人看过
					</view>
				</view>
			</view>
		</view>

		<!-- 评论区 -->
		<view class="comment">
			<view v-if="!commentList.length && noComment">
				<u-empty mode="comment" icon="http://cdn.uviewui.com/uview/empty/comment.png"></u-empty>
			</view>
			<view class="content">
				<view class="item" v-for="item in commentList">
					<comment-item :item="item" @removeEnv="PremoveEnv"></comment-item>
				</view>
			</view>
		</view>
		<!-- 输入框 -->
		<comment-frame :commentObj="commentObj" @commentEnv="PcommentEnv"></comment-frame>
	</view>
</template>

<script>
import pageJson from '@/pages.json';
import { giveName, giveAvatar, likeFun } from '../../utils/tools.js';
import { store } from '@/uni_modules/uni-id-pages/common/store.js';

const db = uniCloud.database();
const utilsObj = uniCloud.importObject('utilsObj', {
	customUI: true //取消自动的加载动画
});
export default {
	data() {
		return {
			artid: '',
			loadState: true, //骨架屏显示
			//富文本的样式
			tagStyle: {
				p: 'line-height: 1.7em; font-size:16px;',
				img: 'margin:10rpx 0'
			},
			//联表查询 的表的集合
			// collections: []
			detailObj: null,
			//点过赞的用户
			likeUserArr: [],
			//发评论 的对象
			commentObj: {
				article_id: '',
				comment_type: 0
			},
			//评论列表
			commentList: [],
			noComment: false //一开始不显示评论区
		};
	},
	onLoad(e) {
		if (!e.id) {
			this.errFun();
			return;
		}
		this.artid = e.id;
		this.commentObj.article_id = e.id;
		this.getData();
		this.readUpdate();
		this.getLikeUser();
		this.getComment();
	},
	methods: {
		giveName,
		giveAvatar,
		//评论成功回调(实现无感操作)
		PcommentEnv(e) {
			this.commentList.unshift({
				...this.commentObj,
				...e, //id和评论内容
				user_id: [store.userInfo]
			});
		},

		//删除评论成功回调
		PremoveEnv(e) {
			//找到删除评论的索引
			let index = this.commentList.findIndex((item) => {
				return item._id === e.id;
			});
			this.commentList.splice(index, 1);
		},

		//获取评论列表
		async getComment() {
			let commentTemp = db.collection('quanzi_comment').where(`article_id == "${this.artid}" && comment_type==0`).orderBy('comment_date desc').limit(5).getTemp();
			let userTemp = db.collection('uni-id-users').field('_id, username, nickname, avatar_file').getTemp();

			let res = await db.collection(commentTemp, userTemp).get();
			
			//统计回复数量，先抽取一级评论集合
			let idArr=res.result.data.map(item =>{
				return item._id
			})
			//分组查询
			let replyArr = await db.collection('quanzi_comment').where({
				reply_comment_id: db.command.in(idArr)
			}).groupBy('reply_comment_id').groupField('count(*) as totalReply').get()
			
			//遍历一级评论，在每次循环中找二级评论的“被回复评论id”与一级评论id相等的
			res.result.data.forEach(item=>{
				let index = replyArr.result.data.findIndex(find=>{
					return find.reply_comment_id === item._id
				})
				//若存在相等，将分组统计的个数赋予一级评论
				if(index > -1){
					item.totalReply = replyArr.result.data[index].totalReply
				}
			})
			
			if (res.result.data.length === 0) this.noComment = true;
			this.commentList = res.result.data;
		},

		//获取点赞的用户
		getLikeUser() {
			let likeTemp = db.collection('quanzi_like').where(`article_id == "${this.artid}"`).getTemp();
			let userTemp = db.collection('uni-id-users').field('_id, avatar_file').getTemp();
			//倒序，再反转，不然叠加顺序不对
			db.collection(likeTemp, userTemp)
				.orderBy('publish_date desc')
				.limit(5)
				.get()
				.then((res) => {
					res.result.data = res.result.data.reverse();
					this.likeUserArr = res.result.data;
				});
		},
		//错误处理
		errFun() {
			uni.showToast({
				title: '参数错误',
				icon: 'none'
			});
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/index/index'
				});
			}, 500);
		},
		async getData() {
			let artTemp = db.collection('quanzi_article').where(`_id == "${this.artid}"`).getTemp();
			let userTemp = db.collection('uni-id-users').field('_id, username, nickname, avatar_file').getTemp();
			let likeTemp = db.collection('quanzi_like').where(`article_id=="${this.artid}" && user_id==$cloudEnv_uid`).getTemp();

			let tempArr = [artTemp, userTemp];
			//已登录，才查like表
			if (store.hasLogin) tempArr.push(likeTemp);

			await db
				.collection(...tempArr)
				.get({
					getOne: true
				})
				.then((res) => {
					if (!res.result.data) {
						this.errFun;
						return;
					}
					console.log('总数据：', res.result.data);
					let isLike = false;

					//已经登录，才判断用户有没有点过喜欢
					if (store.hasLogin) isLike = res.result.data._id?.quanzi_like?.length ? true : false;

					res.result.data.isLike = isLike; //绑定到data上
					this.detailObj = res.result.data;
					this.loadState = false;
					//实时的导航条
					uni.setNavigationBarTitle({
						title: this.detailObj.title
					});
				})
				.catch((err) => {
					console.log('意料之外的错误', err);
				});
		},

		//更新阅读量
		readUpdate() {
			utilsObj.operation('quanzi_article', 'view_count', this.artid, 1);
		},

		//点赞操作
		async clickLike() {
			//判断是否登录
			if (!store.hasLogin) {
				await this.showModalSync();
				return;
			}

			//节流
			let time = Date.now();
			if (time - this.likeTime < 500) {
				uni.showToast({
					title: '操作频繁',
					icon: 'none',
					mask: true //蒙版
				});
				return;
			}
			this.likeTime = time;

			//无感操作：前端来做按钮高亮，不是依靠数据库
			this.detailObj.isLike ? this.detailObj.like_count-- : this.detailObj.like_count++;
			this.detailObj.isLike = !this.detailObj.isLike;

			likeFun(this.artid);
		},
		//点赞操作数据库
		// async likeFun() {
		// 	//判断是否已经点赞 $cloudEnv_uid:用户uid，依赖uni-id
		// 	let count = await db.collection('quanzi_like').where(`article_id=="${this.artid}" && user_id==$cloudEnv_uid`).count();
		// 	if (count.result.total) {
		// 		db.collection('quanzi_like').where(`article_id=="${this.artid}" && user_id==$cloudEnv_uid`).remove();
		// 		utilsObj.operation('quanzi_article', 'like_count', this.artid, -1);
		// 	} else {
		// 		db.collection('quanzi_like').add({
		// 			article_id: this.artid
		// 		});
		// 		//文章表的点赞总数加一
		// 		utilsObj.operation('quanzi_article', 'like_count', this.artid, 1);
		// 	}
		// },
		//点赞之前的校验 将showModal封装为同步方法
		async showModalSync() {
			const res = await new Promise((resolve, reject) => {
				uni.showModal({
					title: '登录后才可进行操作',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/' + pageJson.uniIdRouter.loginPage
							});
							resolve(res);
						} else {
							reject(res);
						}
					}
				});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.detail {
	background: #f8f8f8;
	min-height: calc(100vh - var(--window-top));
	.container {
		padding: 30rpx;
		background: #fff;
		.title {
			font-size: 46rpx;
			color: #333;
			line-height: 1.4em;
			font-weight: 600;
		}
		.userinfo {
			padding: 20rpx 0 50rpx;
			display: flex;
			align-items: center;
			.avatar {
				width: 60rpx;
				height: 60rpx;
				padding-right: 15rpx;
				image {
					width: 100%;
					height: 100%;
					border-radius: 50%;
				}
			}
			.text {
				font-size: 28rpx;
				color: #555;
				.small {
					font-size: 20rpx;
					color: #999;
				}
			}
		}
		.content {
		}
		.like {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 80rpx 50rpx 50rpx;
			.btn {
				width: 260rpx;
				height: 120rpx;
				background: #e4e4e4;
				border-radius: 100rpx;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				font-size: 28rpx;
				.iconfont {
					font-size: 50rpx;
				}
				&.active {
					background: #0199fe;
				}
			}
			.text {
				font-size: 26rpx;
				color: #666;
				.num {
					color: #0199fe;
				}
				.spot {
					padding: 0 10rpx;
				}
			}
			.users {
				display: flex;
				justify-content: center;
				padding: 30rpx 0;
				image {
					width: 50rpx;
					height: 50rpx;
					border-radius: 50%;
					border: 3px solid #fff;
					margin-left: -20rpx;
				}
			}
		}
	}

	// 评论
	.comment {
		padding: 30rppx;
		padding-bottom: 120rpx;
		.item {
			padding: 10rpx 0;
		}
	}
}
</style>
